#include "stdafx.h"
#include <MyFC/WndTipCtrl.h>
				  
namespace My {

void WindowTipCtrl::GetWndTipText(CString& str, CWnd* pWnd) const
{	 	
	assert(::IsWindow(m_hWnd));
	assert(pWnd != NULL);

	TOOLINFO ti;
	FillInWndInfo(ti, pWnd);
	ti.lpszText = str.GetBuffer(256);
	::SendMessage(m_hWnd, TTM_GETTEXT, 0, (LPARAM)&ti);
	str.ReleaseBuffer();	
}

BOOL WindowTipCtrl::AddWindow(CWnd* pWnd, UINT nIDText, LPCRECT lpRectTool) 
{
	assert(::IsWindow(m_hWnd));
	assert(nIDText != 0);
	assert(pWnd != NULL);

	TOOLINFO ti;
	FillInWndInfo(ti, pWnd);
	if (lpRectTool != NULL)
		memcpy(&ti.rect, lpRectTool, sizeof(RECT));
	ti.hinst = AfxFindResourceHandle(MAKEINTRESOURCE((nIDText>>4)+1),
		RT_STRING);
	assert(ti.hinst != NULL);
	ti.lpszText = (LPTSTR)MAKEINTRESOURCE(nIDText);
	return (BOOL) ::SendMessage(m_hWnd, TTM_ADDTOOL, 0, (LPARAM)&ti);
}

BOOL WindowTipCtrl::AddWindow(CWnd* pWnd, LPCTSTR lpszText, LPCRECT lpRectTool)
{
	assert(::IsWindow(m_hWnd));
	assert(pWnd != NULL);
	assert(lpszText != NULL);
	// the toolrect and toolid must both be zero or both valid

	TOOLINFO ti;
	FillInWndInfo(ti, pWnd);
	if (lpRectTool != NULL)
		memcpy(&ti.rect, lpRectTool, sizeof(RECT));
	ti.lpszText = (LPTSTR)lpszText;
	return (BOOL) ::SendMessage(m_hWnd, TTM_ADDTOOL, 0, (LPARAM)&ti);
}

void WindowTipCtrl::DelWindow(CWnd* pWnd)
{
	assert(::IsWindow(m_hWnd));
	assert(pWnd != NULL);

	TOOLINFO ti;
	FillInWndInfo(ti, pWnd);
	::SendMessage(m_hWnd, TTM_DELTOOL, 0, (LPARAM)&ti);
}

void WindowTipCtrl::SetWindowRect(CWnd* pWnd, LPCRECT lpRect)
{
	assert(::IsWindow(m_hWnd));
	assert(pWnd != NULL);

	TOOLINFO ti;
	FillInWndInfo(ti, pWnd);
	memcpy(&ti.rect, lpRect, sizeof(RECT));
	::SendMessage(m_hWnd, TTM_NEWTOOLRECT, 0, (LPARAM)&ti);
}

void WindowTipCtrl::UpdateWndTipText(LPCTSTR lpszText, CWnd* pWnd)
{
	assert(::IsWindow(m_hWnd));
	assert(pWnd != NULL);

	TOOLINFO ti;
	FillInWndInfo(ti, pWnd);
	ti.lpszText = (LPTSTR)lpszText;
	::SendMessage(m_hWnd, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti);
}

void WindowTipCtrl::UpdateWndTipText(UINT nIDText, CWnd* pWnd)
{
	assert(nIDText != 0);

	CString str;
	VERIFY(str.LoadString(nIDText));
	UpdateTipText(str, pWnd);
}

void WindowTipCtrl::FillInWndInfo(TOOLINFO& ti, CWnd* pWnd) const
{
	memset(&ti, 0, sizeof(TOOLINFO));
	ti.cbSize = sizeof(TOOLINFO);
	HWND hwnd = pWnd->GetSafeHwnd();
	ti.hwnd = hwnd;
	ti.uFlags = TTF_SUBCLASS;
	ti.uId = 0;
}

} // My
